#include "uart.h"
#include "ui_uart.h"

Uart::Uart(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Uart)
    , m_isOpen(false)
{
    ui->setupUi(this);
    dbManager = DatabaseManager::instance();
    Uart::UIInit();
    m_pSerialPort = new QSerialPort;

    ui->textEditRecv->setReadOnly(true);
    connect(ui->btnOpenPort,&QPushButton::clicked,this,&Uart::onOpenPort);
    connect(ui->btnMsgSend,&QPushButton::clicked,this,&Uart::onSendMsg);
    connect(ui->btnMsgReceClear,&QPushButton::clicked,this,&Uart::onClearReceBuffer);
    connect(ui->btnMsgSendClear,&QPushButton::clicked,this,&Uart::onClearSendBuffer);

    // 创建一个定时器
    QTimer *timer = new QTimer(this);
    // 连接定时器的 timeout 信号到刷新端口号的槽函数
    connect(timer, &QTimer::timeout, this, &Uart::refreshSerialPorts);
    // 设置定时器的时间间隔为 2 秒
    timer->start(2000);


}

Uart::~Uart()
{
    if (m_pSerialPort->isOpen()) {
        m_pSerialPort->close();
    }
    delete ui;
}

void Uart::UIInit()
{
    //端口号
    Uart::refreshSerialPorts();

    //波特率
    QList<QPair<QString,int>> baudRates{
        {"1200",QSerialPort::Baud1200},
        {"2400",QSerialPort::Baud2400},
        {"4800",QSerialPort::Baud4800},
        {"9600",QSerialPort::Baud9600},
        {"19200",QSerialPort::Baud19200},
        {"38400",QSerialPort::Baud38400},
        {"57600",QSerialPort::Baud57600},
        {"115200",QSerialPort::Baud115200}
    };

    for(const auto &baudRate:baudRates){
        ui->comboBoxBoautrate->addItem(baudRate.first,baudRate.second);
    }

    //数据位
    QList<QPair<QString, QSerialPort::DataBits>> dataBitsList{
        {"5", QSerialPort::Data5},
        {"6", QSerialPort::Data6},
        {"7", QSerialPort::Data7},
        {"8", QSerialPort::Data8}
    };
    for(const auto &dataBit : dataBitsList){
        ui->comboBoxDatabit->addItem(dataBit.first, static_cast<int>(dataBit.second));
    }
    ui->comboBoxDatabit->setCurrentIndex(3);

    //校验位
    QList<QPair<QString, QSerialPort::Parity>> parityList{
        {"NONE", QSerialPort::NoParity},
        {"ODD", QSerialPort::OddParity},
        {"EVEN", QSerialPort::EvenParity},
        {"MARK", QSerialPort::MarkParity},
        {"SPACE", QSerialPort::SpaceParity}
    };
    for(const auto &parity : parityList){
        ui->comboBoxJiaoyan->addItem(parity.first, static_cast<int>(parity.second));
    }

    //停止位
    QList<QPair<QString, QSerialPort::StopBits>> stopBitsList{
        {"1", QSerialPort::OneStop},
        {"1.5", QSerialPort::OneAndHalfStop},
        {"2", QSerialPort::TwoStop}
    };
    for(const auto &stopBit : stopBitsList){
        ui->comboBoxStop->addItem(stopBit.first, static_cast<int>(stopBit.second));
    }
    ui->comboBoxStop->setCurrentIndex(0);

    //流控制
    QList<QPair<QString, QSerialPort::FlowControl>> flowControlList{
        {"NONE", QSerialPort::NoFlowControl},
        {"RTS/RCS", QSerialPort::HardwareControl},
        {"XON/XOF", QSerialPort::SoftwareControl}
    };
    for(const auto &flowControl : flowControlList){
        ui->comboBoxFileCon->addItem(flowControl.first, static_cast<int>(flowControl.second));
    }
    ui->comboBoxFileCon->setCurrentIndex(0);

}



void Uart::refreshSerialPorts()
{
    // 记录当前选中的串口
    QString currentPort = ui->comboBoxSerialPort->currentText();
    // 清空下拉列表框
    ui->comboBoxSerialPort->clear();
    // 获取可用的串口信息
    auto serialPortInfos = QSerialPortInfo::availablePorts();
    for(const auto &portInfo : serialPortInfos){
        ui->comboBoxSerialPort->addItem(portInfo.portName(), portInfo.portName());
    }
    // 重新设置之前选中的串口
    int index = ui->comboBoxSerialPort->findText(currentPort);
    if (index != -1) {
        ui->comboBoxSerialPort->setCurrentIndex(index);
    } else if (ui->comboBoxSerialPort->count() > 0) {
        ui->comboBoxSerialPort->setCurrentIndex(0);
    }
}

void Uart::onOpenPort()
{
    if (m_isOpen) {
        // 关闭串口
        m_pSerialPort->close();
        disconnect(m_pSerialPort, &QSerialPort::readyRead, this, &Uart::onReadData);
        ui->btnOpenPort->setText("打开串口");
        m_isOpen = false;

        // 打开串口关闭后，恢复设置项的可编辑状态
        ui->comboBoxSerialPort->setEnabled(true);
        ui->comboBoxBoautrate->setEnabled(true);
        ui->comboBoxDatabit->setEnabled(true);
        ui->comboBoxJiaoyan->setEnabled(true);
        ui->comboBoxStop->setEnabled(true);
        ui->comboBoxFileCon->setEnabled(true);

    } else {
        m_pSerialPort->setPortName(ui->comboBoxSerialPort->currentText());
        m_pSerialPort->setBaudRate(ui->comboBoxBoautrate->currentText().toInt());
        m_pSerialPort->setDataBits(static_cast<QSerialPort::DataBits>(ui->comboBoxDatabit->currentData().toInt()));
        m_pSerialPort->setParity(static_cast<QSerialPort::Parity>(ui->comboBoxJiaoyan->currentData().toInt()));
        m_pSerialPort->setStopBits(static_cast<QSerialPort::StopBits>(ui->comboBoxStop->currentData().toInt()));
        m_pSerialPort->setFlowControl(static_cast<QSerialPort::FlowControl>(ui->comboBoxFileCon->currentData().toInt()));
        if (m_pSerialPort->open(QSerialPort::ReadWrite)) {
            ui->btnOpenPort->setText("关闭串口");
            connect(m_pSerialPort, &QSerialPort::readyRead, this, &Uart::onReadData);
            m_isOpen = true;
            // 打开串口后，禁用设置项
            ui->comboBoxSerialPort->setEnabled(false);
            ui->comboBoxBoautrate->setEnabled(false);
            ui->comboBoxDatabit->setEnabled(false);
            ui->comboBoxJiaoyan->setEnabled(false);
            ui->comboBoxStop->setEnabled(false);
            ui->comboBoxFileCon->setEnabled(false);
        } else {
            qDebug() << "Failed to open serial port";
            m_pSerialPort->close();
            ui->btnOpenPort->setText("打开串口");
            m_isOpen = false;
        }
    }
}

void Uart::onSendMsg()
{
    if(m_isOpen){
        QString sendData = ui->textEditSend->toPlainText();
        if(!sendData.isEmpty()){
            qint64 writeBuff = m_pSerialPort->write(sendData.toUtf8());
            if(writeBuff == -1){
                qDebug() << "发送失败";
            }else{
                qDebug() << "发送成功";
            }

        }
    }else{
        qDebug() << "串口打开失败";
    }
}

void Uart::onClearReceBuffer()
{
    ui->textEditRecv->clear();
}

void Uart::onClearSendBuffer()
{
    if(ui->textEditSend->toPlainText().isEmpty()){
        return;
    }
    ui->textEditSend->clear();
}

void Uart::setDataMonitoring(DataMonitoring* dm)
{
    m_pDataMonitoring = dm;
}

void Uart::onReadData()
{
    QByteArray data = m_pSerialPort->readAll();
    ui->textEditRecv->append(data);

    // 解析数据并写入数据库
    // 假设数据格式为: "temp:25.5,humidity:60.5,device:1"
    QString strData = QString::fromUtf8(data).trimmed();
    QStringList parts = strData.split(',');

    double temp = 0.0;
    double humidity = 0.0;
    int deviceId = 1; // 默认设备ID

    for(const QString& part : parts) {
        if(part.startsWith("temp:")) {
            temp = part.mid(5).toDouble();
        } else if(part.startsWith("humidity:")) {
            humidity = part.mid(9).toDouble();
        } else if(part.startsWith("device:")) {
            deviceId = part.mid(7).toInt();
        }
    }

    // 获取当前时间戳
    QString timestamp = QDateTime::currentDateTime().toString(Qt::ISODate);

    // 构建SQL插入语句
    QString sql = QString("INSERT INTO data (device_id, timestamp, temperature, humidity) "
                       "VALUES (%1, '%2', %3, %4,%5)")
                       .arg(deviceId)
                       .arg(timestamp)
                       .arg(temp)
                       .arg(humidity);

    QString response = dbManager->sendRequest(sql);
}
